package com.ag.improvedjava.iterable;

import java.util.Comparator;
import java.util.Iterator;

final class SequenceEqual<T> {

	private final Iterable<T> first;
	private final Iterable<T> second;
	private final Comparator<T> comparer;

	SequenceEqual(Iterable<T> first, Iterable<T> second) {
		this.first = first;
		this.second = second;
		this.comparer = equalityComparator();
	}

	SequenceEqual(Iterable<T> first, Iterable<T> second, Comparator<T> comparer) {
		this.first = first;
		this.second = second;
		this.comparer = (comparer == null) ? equalityComparator() : comparer;
	}

	boolean value() {
		Iterator<T> itFirst = first.iterator();
		Iterator<T> itSecond = second.iterator();
		while (itFirst.hasNext() && itSecond.hasNext()) { 
			if (comparer.compare(itFirst.next(), itSecond.next()) != 0) {
				return false;
			}
		}
		return !itFirst.hasNext() && !itSecond.hasNext();
	}
	
	private Comparator<T> equalityComparator() {
		return new Comparator<T>() {
			@Override
			public int compare(T o1, T o2) {
				return o1.equals(o2) ? 0 : -1;
			}
		};
	}
}